package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ltmonitor.entity.BasicData;
import com.ltmonitor.service.IBaseService;
import com.ltmonitor.service.IBasicDataService;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.vo.TreeNode;

/**
 * 基础数据的查询，维护Action
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/basicData")
public class BasicDataAction extends PersistenceAction<Long, BasicData> {
	
	public BasicDataAction()
	{
		EditViewName = "/basicData/editBasicData";
	}
	

	@RequestMapping("/viewList.action")
	public String list()
	{
		return "/basicData/basicDataList";
	}

	@RequestMapping("/informationList.action")
	public String informationList()
	{
		return "/basicData/informationList";
	}

	/**
	 * 新增后的保存操作
	 *
	 * @return
	 */
	@RequestMapping("/viewInformation.action")
	public ModelAndView viewInformation(Model model,
							 @RequestParam(value = "entityId", required = false) long id) {

		ModelAndView m = new ModelAndView();
		m.setViewName("/basicData/editInformation");
		try {
			if (id > 0) {
				BasicData t = this.basicDataService.load(id);
				if(t == null)
				{
					Map entity = new HashMap();
					entity.put("entityId", 0);
					m.addObject("entity", entity);
				}else
					m.addObject("entity", t);
			}else
			{
				Map entity = new HashMap();
				entity.put("entityId", 0);
				m.addObject("entity", entity);
			}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addObject("发生错误:"+ex.getMessage());
		}

		return m;
	}

	/**
	 * 获取某一类型的基础数据 用于前台生成下拉框列表
	 */
	@RequestMapping("/query.action")
	@ResponseBody
	public JsonMessage execute(String category, String parent, String queryID) {
		List results = new ArrayList();
		try {
			if (category != null) {
				// 查询基础数据表
				List<BasicData> ls = getBasicDataService()
						.getBasicDataByParentCode(category);
				for (BasicData b : ls) {
					HashMap item = new HashMap();
					item.put("name", b.getName());
					item.put("code", b.getCode());
					results.add(item);
				}
			} else if (queryID != null) {
				// 根据Ibatis的queryId, 来调用Ibatis查询
				Map params = this.getParams();
				if (this.getOnlineUser() != null)
					params.put("userId", this.getOnlineUser().getEntityId());
				if(queryID.equals("selectRoleList") && this.getOnlineUser().getCompanyId() > 0)
				{
					//只显示上级部门共享的角色和本部门已有的角色
				   List<Long> depIdList = super.getDepartmentService().getParentDepIdList(this.getOnlineUser().getCompanyId());
				   params.put("parentCompanyIdList", depIdList);
				}
				
				results = this.queryService.query(queryID, params);
			}

			return json(true, results);
		} catch (Exception ex) {
			super.log.error(ex.getMessage());
			super.log.error(ex.getStackTrace());
			return json(false, ex.getMessage());
		}
	}

	@RequestMapping("/comboTree.action")
	@ResponseBody
	public List<TreeNode> tree(String queryID) {

		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		try {
			if (queryID != null) {
				// 根据Ibatis的queryId, 来调用Ibatis查询
				Map params = this.getParams();
				List results = this.queryService.query(queryID, params);

				Map<String, TreeNode> nodeMap = new HashMap<String, TreeNode>();
				for (Object obj : results) {
					Map rowData = (Map) obj;
					String parentId = "" + rowData.get("pId");
					String id = "" + rowData.get("id");
					String code = "" + rowData.get("code");
					String name = "" + rowData.get("name");
					TreeNode node = new TreeNode("" + id, name, parentId,
							"icon-polygon");
					node.setState("open");
					node.setLeaf(true);
					nodeMap.put(node.getId(), node);
				}
				for (TreeNode node : nodeMap.values()) {
					if (StringUtil.isNullOrEmpty(node.getPid()) == false) {
						TreeNode parentNode = nodeMap.get(node.getPid());
						if (parentNode != null) {
							parentNode.getChildren().add(node);
							node.setState("closed");
							parentNode.setLeaf(false);
						} else
							nodeList.add(node);
					} else
						nodeList.add(node);
				}

			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}

		return nodeList;
	}

	/**
	 * 新增后的保存操作
	 * 
	 * @return
	 */
	@RequestMapping("/save.action")
	public ModelAndView save(HttpServletRequest request, Model model,
			 BasicData entity)  {

		ModelAndView m = new ModelAndView();
		m.setViewName(EditViewName);
		try {
			BasicData bd = (BasicData) entity;
			if (bd.getParent() == null || bd.getParent().length() == 0)
				bd.setParent("Root");
			String hql = "from BasicData where code = ? and parent = ? and entityId <> ? and deleted = ?";
			Object obj = this.basicDataService.find(
					hql,
					new Object[] { bd.getCode(), bd.getParent(),
							bd.getEntityId(), false });
			if (obj != null) {
				m.addObject("message", "保存失败,数据字典编码重复，请重新编码");
			} else {
				basicDataService.saveOrUpdate(bd);
				m.addObject("message", "保存成功");
			}
			m.addObject("entity", bd);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addObject("message", ex.getMessage());
		}

		return m;
	}
	/**
	 * 新增后的保存操作
	 *
	 * @return
	 */
	@RequestMapping("/saveInformation.action")
	public ModelAndView saveInformation(HttpServletRequest request, Model model,
							 BasicData entity)  {

		ModelAndView m = new ModelAndView();
		m.setViewName("/basicData/editInformation");
		try {
			BasicData bd = (BasicData) entity;
			if (bd.getParent() == null || bd.getParent().length() == 0)
				bd.setParent("Root");
			/**
			String hql = "from BasicData where code = ? and parent = ? and entityId <> ? and deleted = ?";
			Object obj = this.basicDataService.find(
					hql,
					new Object[] { bd.getCode(), bd.getParent(),
							bd.getEntityId(), false });
			if (obj != null) {
				m.addObject("message", "保存失败,数据字典编码重复，请重新编码");
			} else {
			 */
				basicDataService.saveOrUpdate(bd);
				m.addObject("message", "保存成功");
			//}
			m.addObject("entity", bd);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addObject("message", ex.getMessage());
		}

		return m;
	}

}
